package com.lwq.imserver.service;

import com.lwq.imserver.model.ChatMessage;
import com.lwq.imserver.model.ChatRoom;
import com.lwq.imserver.model.system.SysUser;
import com.lwq.imserver.util.ListUtil;
import com.lwq.imserver.util.WebSocketUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2022/1/29 22:15
 */
@Service
public class ChatRoomService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<ChatRoom> queryByUserId(String userId) {
        return mongoTemplate.find(Query.query(Criteria.where("members.id").is(userId)).with(Sort.by(Sort.Order.desc("createDate"))), ChatRoom.class);
    }

    public void add(ChatRoom chatRoom) {
        if (chatRoom.getMembers().isEmpty()) throw new RuntimeException("系统错误");
        List<ChatRoom> chatRooms = mongoTemplate.find(new Query(), ChatRoom.class);
        Boolean flag = true;
        for (ChatRoom e : chatRooms) {
            if (ListUtil.listIsAllEqueal(e.getMembers().stream().map(i -> i.getId()).collect(Collectors.toList()),
                    chatRoom.getMembers().stream().map(i -> i.getId()).collect(Collectors.toList()))) {
                flag = false;
            }
        }
        if (!flag) throw new RuntimeException("已有该成员的房间,不要重复创建!");
        chatRoom.setTimestamp(Calendar.getInstance().getTimeInMillis());
        mongoTemplate.insert(chatRoom);
        WebSocketUtil.chatRoomList.add(chatRoom);
        WebSocketUtil.broadCastAddRoom(chatRoom);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String id, String userId) {
        ChatRoom chatRoom = mongoTemplate.findById(id, ChatRoom.class);
        if (chatRoom == null || chatRoom.getMembers().isEmpty()
                || !chatRoom.getMembers().stream()
                .map(e -> e.getId()).collect(Collectors.toList()).contains(userId)) throw new RuntimeException("系统异常");
        List<SysUser> members = chatRoom.getMembers();
        chatRoom.setMembers(members.stream().filter(e -> !e.getId().equals(userId)).collect(Collectors.toList()));
        if (chatRoom.getMembers().isEmpty() || chatRoom.getMembers().size() == 1) {
            mongoTemplate.remove(Query.query(Criteria.where("roomId").is(id)), ChatMessage.class);
            mongoTemplate.findAndRemove(Query.query(Criteria.where("id").is(id)), ChatRoom.class);
        } else {
            mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(id)), Update.update("members", chatRoom.getMembers()), ChatRoom.class);
        }
        WebSocketUtil.broadCastRemoveRoom(chatRoom.getMembers().stream().map(e -> e.getId()).collect(Collectors.toList()), userId,chatRoom);
    }
}
